﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace VH.SharePoint.Api.Helpers
{
    public class SPUnsafeUpdate : IDisposable
    {
        private bool _defaultWebUnsafe ;
        private bool _defaultSiteUnsafe;
        private SPWeb _web;
        private SPSite _site;

        public SPUnsafeUpdate()
            : this(SPContext.Current.Site, SPContext.Current.Web)
        {
        }

        public SPUnsafeUpdate(SPSite site) 
            : this(site, null)
        {
        }

        public SPUnsafeUpdate(SPWeb web)
            : this(null, web)
        {
        }


        public SPUnsafeUpdate(SPSite site, SPWeb web)
        {
            if (site != null)
            {
                _defaultSiteUnsafe = site.AllowUnsafeUpdates;
                _site = site;
                _site.AllowUnsafeUpdates = true;
            }
            if (web != null)
            {
                _defaultWebUnsafe = web.AllowUnsafeUpdates;
                _web = web;
                _web.AllowUnsafeUpdates = true;
            }
        }


        public void Dispose()
        {
            if (_site != null)
            {
                _site.AllowUnsafeUpdates = _defaultSiteUnsafe;
            }
            if (_web != null)
            {
                _web.AllowUnsafeUpdates= _defaultWebUnsafe;
            }
        }
    }
}
